import 'package:json_annotation/json_annotation.dart';

part 'base_response.g.dart';

// MIFFY接口： "code":"ok","msg":"","data":
// 瑞云接口： "code": 0 ,"Message":"","Data":
// ciot接口： "code":200,"msg":"","data":

// 泛型响应类
@JsonSerializable(genericArgumentFactories: true)
class BaseResponse<T> {
  @JsonKey(name: 'code', fromJson: _getCode)
  final dynamic code;

  @JsonKey(name: 'msg', fromJson: _getMessage)
  final String msg;

  final T? data;

  BaseResponse({required this.code, required this.msg, this.data});

  // 从多种可能的字段获取code（不进行转换，直接返回）
  static dynamic _getCode(dynamic json) {
    return json; // 直接返回原始值，无论是 int 还是 String
  }

  // 从多种可能的字段获取消息
  static String _getMessage(dynamic json) {
    if (json is Map<String, dynamic>) {
      return json['msg'] ?? json['Message'] ?? ''; // Message 对应瑞云服务
    }
    return '';
  }

  factory BaseResponse.fromJson(
    Map<String, dynamic> json,
    T Function(Object? json) fromJsonT,
  ) {
    return BaseResponse<T>(
      code: _getCode(json['code']),
      msg: _getMessage(json),
      data:
          json['data'] != null ||
              json['Data'] !=
                  null // Data 对应瑞云服务
          ? fromJsonT(json['data'] ?? json['Data'])
          : null,
    );
  }

  Map<String, dynamic> toJson(Object? Function(T value) toJsonT) {
    return _$BaseResponseToJson(this, toJsonT);
  }
}
